package me.ingxin.android.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import android.view.animation.Interpolator
import kotlin.math.pow

/**
 * Created by ingxin on 2022/5/31
 * 水平loading动画
 */
class HorizontalLoadingView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val paint = Paint()
    private var progress = 0
    private var valueAnimator: ValueAnimator? = null

    /**动画颜色*/
    var color = Color.WHITE

    /**动画执行时间*/
    var duration = 800L

    init {
        paint.isAntiAlias = true
        paint.color = color
    }

    override fun onDraw(canvas: Canvas) {
        val r = Color.red(color)
        val g = Color.green(color)
        val b = Color.blue(color)

        val alpha = when {
            progress < 60 -> (4.25f * progress).toInt()
            progress <= 90 -> 255
            else -> (-25.5f * progress + 2550).toInt()
        }

        paint.color = Color.argb(alpha, r, g, b)

        val w = width * progress / 100f
        val h = height.toFloat()
        val dx = (width - w) / 2f
        canvas.drawRect(dx, 0f, width - dx, h, paint)
    }

    /***
     * 开始动画
     */
    fun start() {
        valueAnimator?.cancel()
        valueAnimator = ValueAnimator.ofInt(0, 100).apply {
            duration = this@HorizontalLoadingView.duration
            repeatCount = ValueAnimator.INFINITE
            repeatMode = ValueAnimator.RESTART
            interpolator = MyInterpolator()
        }

        valueAnimator?.addUpdateListener {
            progress = it.animatedValue as Int
            invalidate()
        }
        valueAnimator?.start()
    }

    /**
     * 停止动画
     */
    fun stop() {
        valueAnimator?.cancel()
        valueAnimator = null
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stop()
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        start()
    }

    override fun onVisibilityChanged(changedView: View, visibility: Int) {
        super.onVisibilityChanged(changedView, visibility)
        if (visibility == VISIBLE) {
            start()
        } else {
            stop()
        }
    }

    /**
     * 先加速然后停止一段,最后减速.
     */
    private class MyInterpolator : Interpolator {

        override fun getInterpolation(input: Float): Float {
            return when {
                input < 0.475 -> (2 * input.toDouble()).pow(2.0).toFloat()
                else -> 1 - (0.6 * input.toDouble() - 0.6).pow(2.0).toFloat()
            }
        }
    }


}